package com.sghd.fight;

import com.sghd.common.console.Console;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

/**
 * @author wch
 * @date 2018-10-17 14:00
 * @desc
 **/
public class RobotApp {
    private static final Logger logger = LoggerFactory.getLogger(RobotApp.class);
    /** 默认的上下文配置名 */
    private static final String DEFAULT_APPLICATION_CONTEXT = "applicationContext.xml";

    public static void main(String[] arguments) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(DEFAULT_APPLICATION_CONTEXT);
        try {
            logger.debug("机器人服务初始化完成，开启服务器控制台");
            Console console = new Console(applicationContext);
            console.start();
            saveProcessId();
        } catch (Exception exception) {
            logger.error("发生未知错误！", exception);
            if (applicationContext.isRunning()) {
                applicationContext.destroy();
            }
        }
    }
    public static final void saveProcessId() {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        Integer processId = Integer.valueOf(runtimeMXBean.getName().split("@")[0]);
        try {
            File file = new File("pid");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(processId + "");
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            logger.error("PID[{}]文件生成失败！", processId, e);
        }
    }
}
